import { applyMiddleware, createStore } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from 'redux-thunk'

export type Todo = {
  id: number
  content: string
  completed: boolean
}

export type TodoState = {
  list: Todo[]
  type: 'all' | 'active' | 'completed'
}

const initState: TodoState = {
  // 初始化数据的时候有提示了
  // 🎯注意点1：JSON.parse(text: string)
  list: JSON.parse(localStorage.getItem('todos-list') || '[]'),
  // 🎯注意点2：TS 只能推导出来是 string ，可通过 as 断言指定正确类型
  type: (localStorage.getItem('todos-type') as TodoState['type']) || 'all',
}

type TodoAction =
  | { type: 'todo/delById'; payload: number }
  | { type: 'todo/changeCompleted'; payload: number }
  | { type: 'todo/clearCompleted' }
  // 🔔 通过索引签名 TodoState['type'] 获取大类型中定义的小类型
  | { type: 'todo/changeType'; payload: TodoState['type'] }
  | { type: 'todo/changeCheckAll'; payload: boolean }
  | { type: 'todo/addTodo'; payload: Todo }

// 根据 id 删除
export const delById = (id: number): TodoAction => {
  return { type: 'todo/delById', payload: id }
}

// 根据 id 更新完成状态
export const changeCompleted = (id: number): TodoAction => {
  return { type: 'todo/changeCompleted', payload: id }
}

// 删除已完成任务
export const clearCompleted = (): TodoAction => {
  return { type: 'todo/clearCompleted' }
}

// 高亮切换效果
export const changeType = (type: TodoState['type']): TodoAction => {
  return { type: 'todo/changeType', payload: type }
}

// 切换全选状态
export const changeCheckAll = (type: boolean): TodoAction => {
  return { type: 'todo/changeCheckAll', payload: type }
}

// 添加 todo
export const addTodo = (payload: Todo): TodoAction => {
  return { type: 'todo/addTodo', payload }
}

const reducer = function (state = initState, action: TodoAction) {
  // 根据 id 删除
  switch (action.type) {
    case 'todo/delById':
      return { ...state, list: state.list.filter((v) => v.id !== action.payload) }
    // 根据 id 更新完成状态
    case 'todo/changeCompleted':
      return {
        ...state,
        list: state.list.map((item) => {
          if (item.id === action.payload) {
            return { ...item, completed: !item.completed }
          } else {
            return item
          }
        }),
      }
    // 删除已完成任务
    case 'todo/clearCompleted':
      return { ...state, list: state.list.filter((v) => !v.completed) }
    // 高亮切换效果
    case 'todo/changeType':
      return { ...state, type: action.payload }
    // 切换全选状态
    case 'todo/changeCheckAll':
      return { ...state, list: state.list.map((item) => ({ ...item, completed: action.payload })) }
    case 'todo/addTodo':
      return { ...state, list: [action.payload, ...state.list] }
    default:
      return state
  }
}

const store = createStore(reducer, composeWithDevTools(applyMiddleware(thunk)))

export default store
